/************************************************
*  AMS: LAB16                                   * 
*  LM75 and the Mega32 2-wire Interface         *
*                                               *
*  STK500 setup:                                *
*    Header "RS232 spare" connected to RXD/TXD: *
*      RXD = PORTD, bit0                        *
*      TXD = PORTD, bit1                        *
*    I2C data bus (LM75 slaves):                *
*      SCL connected to PORTC, bit0             *
*      SDA connected to PORTC, bit1             *
*    Two LM75 slaves powered from STK500:       *
*      Address no.1 = 0.                        *
*      Address no.2 = 7.                        *
*                                               *
*   Henning Hargaard, January 11, 2012          * 
*************************************************/
#include <avr/io.h>
#define F_CPU 3686400
#include <avr/delay.h>
#include "TempI2CDriver.h"

void i2c_init()
{
  // ---> Write code here to initialize the TWBR register
  // LM75 clock has be to be lower than 400 kHz (according to LM75 data sheet) 
  // The TWBR must be at least 10 in master mode (Mega32 data book)
  
  TWBR = 44;
  TWSR |= 0b00000001;
  
  //TwINT, AKck enable, start, stop, ----, enable ---- interrupt enable.
  // TWCR = 0b11100100; 
}

void i2c_start()
{
  TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
  while ((TWCR & (1<<TWINT)) == 0)
  {}  	
}

void i2c_write(unsigned char data)
{
  TWDR = data;
  TWCR = (1<<TWINT) | (1<<TWEN);
  while ((TWCR & (1<<TWINT)) == 0)
  {}	
}

unsigned char i2c_read (unsigned char isLast)
{
  if (isLast == 0) //If we want to read more than 1 byte
    TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
  else             //If we want to read only one byte
    TWCR = (1<<TWINT) | (1<<TWEN);
  while ((TWCR & (1<<TWINT)) == 0)
  {}
  return TWDR;
}

void i2c_stop()
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
}

// Reads the temperature register from specified sensor
// SensorAddress is between 0 and 7
int LM75_temperature(unsigned char SensorAddress)
{
  // ---> Write code here to read the specified sensor
  // ---> and return the temperature (in 1/2 centigrades) 
  int temp = -300;
  
  if(SensorAddress >= 0 && SensorAddress < 8)
  {
	i2c_start();  
	i2c_write(0b10010000 | (SensorAddress << 1) | 1);
	temp = i2c_read(0);
	i2c_read(1);
	temp = temp << 1;
	i2c_stop();
  }

  return temp/2;	
}